<template>
  <div class="notifications-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>通知管理</span>
          <el-button type="primary" @click="handleAdd" v-if="isAdmin">
            <el-icon><Plus /></el-icon>
            新增通知
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="通知类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="信息" value="info" />
            <el-option label="警告" value="warn" />
            <el-option label="错误" value="error" />
            <el-option label="成功" value="success" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="push_count" label="推送用户数" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.push_count || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button
              v-if="isAdmin && row.status === 1"
              type="success"
              link
              size="small"
              @click="handlePush(row)"
              :loading="pushLoading[row.id]"
            >
              推送
            </el-button>
            <el-button
              v-if="isAdmin"
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="isAdmin"
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑通知对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
      v-if="isAdmin"
    >
      <el-form
        ref="notificationFormRef"
        :model="notificationForm"
        :rules="notificationFormRules"
        label-width="100px"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="notificationForm.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notificationForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入通知内容"
          />
        </el-form-item>
        <el-form-item label="通知类型" prop="type">
          <el-select v-model="notificationForm.type" placeholder="请选择通知类型" style="width: 100%">
            <el-option label="信息" value="info" />
            <el-option label="警告" value="warn" />
            <el-option label="错误" value="error" />
            <el-option label="成功" value="success" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-radio-group v-model="notificationForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 通知详情对话框 -->
    <el-dialog v-model="detailVisible" title="通知详情" width="700px">
      <el-descriptions :column="1" border v-if="notificationDetail">
        <el-descriptions-item label="标题">{{ notificationDetail.title }}</el-descriptions-item>
        <el-descriptions-item label="内容">
          <div style="white-space: pre-wrap; word-break: break-word">{{ notificationDetail.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag :type="getTypeTagType(notificationDetail.type)" size="small">
            {{ getTypeLabel(notificationDetail.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="notificationDetail.status === 1 ? 'success' : 'danger'" size="small">
            {{ notificationDetail.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="推送用户数">
          <span>{{ notificationDetail.push_count || 0 }} 人</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(notificationDetail.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(notificationDetail.updated_at) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button
          v-if="isAdmin && notificationDetail?.status === 1"
          type="success"
          @click="handlePushFromDetail"
          :loading="pushLoading[notificationDetail?.id || '']"
        >
          推送通知
        </el-button>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 推送通知对话框 -->
    <el-dialog v-model="pushVisible" title="推送通知" width="600px" v-if="isAdmin">
      <el-form label-width="120px">
        <el-form-item label="通知标题">
          <el-input :value="pushNotificationTitle" disabled />
        </el-form-item>
        <el-form-item label="推送范围">
          <el-radio-group v-model="pushForm.pushToAll">
            <el-radio :label="true">推送给所有启用用户</el-radio>
            <el-radio :label="false">推送给指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择用户" v-if="!pushForm.pushToAll">
          <el-select
            v-model="pushForm.user_ids"
            placeholder="请选择用户"
            multiple
            filterable
            style="width: 100%"
            :loading="userListLoading"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.nickname} (${user.username})`"
              :value="user.id"
            >
              <span>{{ user.nickname }}</span>
              <span style="color: #8492a6; font-size: 13px; margin-left: 8px">
                {{ user.username }}
              </span>
            </el-option>
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 4px">
            可多选，留空则推送给所有启用用户
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pushVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPush" :loading="pushConfirmLoading">
          确定推送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getNotificationList,
  createNotification,
  updateNotification,
  deleteNotification,
  getNotificationDetail,
  pushNotification,
  type NotificationData,
  type CreateNotificationParams,
  type UpdateNotificationParams,
  type NotificationListParams,
  type PushNotificationParams
} from '@/api/notifications'
import { formatDate } from '@/utils'
import { getUserList, type UserData } from '@/api/users'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const isAdmin = computed(() => userStore.userInfo?.is_admin === 1)

const loading = ref(false)
const submitLoading = ref(false)
const pushLoading = ref<Record<string, boolean>>({})
const pushConfirmLoading = ref(false)
const userListLoading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const pushVisible = ref(false)
const isEdit = ref(false)
const notificationFormRef = ref<FormInstance>()
const notificationDetail = ref<NotificationData | null>(null)
const pushNotificationId = ref<string>('')
const pushNotificationTitle = ref<string>('')
const userList = ref<UserData[]>([])

const searchForm = reactive<NotificationListParams>({
  type: undefined,
  status: undefined
})

const pushForm = reactive<{
  pushToAll: boolean
  user_ids: string[]
}>({
  pushToAll: true,
  user_ids: []
})

const tableData = ref<NotificationData[]>([])

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const notificationForm = reactive<CreateNotificationParams & { id?: string; status?: number }>({
  title: '',
  content: '',
  type: 'info',
  status: 1
})

const notificationFormRules: FormRules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择通知类型', trigger: 'change' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑通知' : '新增通知'))

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    info: 'info',
    warn: 'warning',
    error: 'danger',
    success: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    info: '信息',
    warn: '警告',
    error: '错误',
    success: '成功'
  }
  return labelMap[type] || type
}

// 加载通知列表
const loadNotificationList = async () => {
  loading.value = true
  try {
    const params: NotificationListParams = {
      page: pagination.page,
      pageSize: pagination.size,
      ...searchForm
    }
    // 移除 undefined 值
    Object.keys(params).forEach(key => {
      if (params[key as keyof NotificationListParams] === undefined) {
        delete params[key as keyof NotificationListParams]
      }
    })

    const res = await getNotificationList(params)
    tableData.value = res.data.list
    pagination.total = res.data.total
    pagination.page = res.data.page
    pagination.size = res.data.pageSize
  } catch (error: any) {
    ElMessage.error(error.message || '加载通知列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadNotificationList()
}

// 重置
const handleReset = () => {
  searchForm.type = undefined
  searchForm.status = undefined
  pagination.page = 1
  loadNotificationList()
}

// 新增通知
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetNotificationForm()
}

// 编辑通知
const handleEdit = async (row: NotificationData) => {
  isEdit.value = true
  dialogVisible.value = true
  loading.value = true
  try {
    const res = await getNotificationDetail({ id: row.id })
    const notification = res.data
    notificationForm.id = notification.id
    notificationForm.title = notification.title
    notificationForm.content = notification.content
    notificationForm.type = notification.type
    notificationForm.status = notification.status
  } catch (error: any) {
    ElMessage.error(error.message || '获取通知详情失败')
    dialogVisible.value = false
  } finally {
    loading.value = false
  }
}

// 删除通知
const handleDelete = (row: NotificationData) => {
  ElMessageBox.confirm(`确定要删除通知 "${row.title}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteNotification({ id: row.id })
        ElMessage.success('删除成功')
        loadNotificationList()
      } catch (error: any) {
        ElMessage.error(error.message || '删除失败')
      }
    })
    .catch(() => {})
}

// 查看详情
const handleViewDetail = async (row: NotificationData) => {
  detailVisible.value = true
  loading.value = true
  try {
    const res = await getNotificationDetail({ id: row.id })
    notificationDetail.value = res.data
  } catch (error: any) {
    ElMessage.error(error.message || '获取通知详情失败')
    detailVisible.value = false
  } finally {
    loading.value = false
  }
}

// 加载用户列表
const loadUserList = async () => {
  if (userList.value.length > 0) {
    return // 已加载过，不再重复加载
  }
  userListLoading.value = true
  try {
    const res = await getUserList({ page: 1, pageSize: 1000, status: 1 }) // 只加载启用状态的用户
    userList.value = res.data.list
  } catch (error: any) {
    ElMessage.error(error.message || '加载用户列表失败')
  } finally {
    userListLoading.value = false
  }
}

// 推送通知
const handlePush = async (row: NotificationData) => {
  if (row.status !== 1) {
    ElMessage.warning('只能推送已启用的通知')
    return
  }
  pushNotificationId.value = row.id
  pushNotificationTitle.value = row.title
  pushForm.pushToAll = true
  pushForm.user_ids = []
  pushVisible.value = true
  await loadUserList()
}

// 从详情对话框推送
const handlePushFromDetail = async () => {
  if (!notificationDetail.value) return
  await handlePush(notificationDetail.value)
}

// 确认推送
const confirmPush = async () => {
  if (!pushNotificationId.value) return

  pushConfirmLoading.value = true
  try {
    const params: PushNotificationParams = {
      id: pushNotificationId.value
    }

    // 如果选择推送给指定用户，且已选择用户
    if (!pushForm.pushToAll && pushForm.user_ids.length > 0) {
      params.user_ids = pushForm.user_ids
    }

    const res = await pushNotification(params)
    ElMessage.success(res.data.message || '推送成功')
    pushVisible.value = false
    // 刷新列表以更新推送用户数
    loadNotificationList()
    // 如果详情对话框打开，刷新详情
    if (detailVisible.value && notificationDetail.value?.id === pushNotificationId.value) {
      const detailRes = await getNotificationDetail({ id: pushNotificationId.value })
      notificationDetail.value = detailRes.data
    }
  } catch (error: any) {
    ElMessage.error(error.message || '推送失败')
  } finally {
    pushConfirmLoading.value = false
  }
}

// 重置表单
const resetNotificationForm = () => {
  notificationForm.title = ''
  notificationForm.content = ''
  notificationForm.type = 'info'
  notificationForm.status = 1
  notificationForm.id = undefined
  notificationFormRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  if (!notificationFormRef.value) return

  await notificationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value) {
          // 更新通知
          const updateParams: UpdateNotificationParams = {
            id: notificationForm.id!,
            title: notificationForm.title,
            content: notificationForm.content,
            type: notificationForm.type,
            status: notificationForm.status
          }
          await updateNotification(updateParams)
          ElMessage.success('更新成功')
        } else {
          // 创建通知
          const createParams: CreateNotificationParams = {
            title: notificationForm.title,
            content: notificationForm.content,
            type: notificationForm.type
          }
          await createNotification(createParams)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        loadNotificationList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '创建失败'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetNotificationForm()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadNotificationList()
}

// 页码改变
const handlePageChange = (page: number) => {
  pagination.page = page
  loadNotificationList()
}

onMounted(() => {
  loadNotificationList()
})
</script>

<style scoped lang="scss">
.notifications-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    > div {
      display: flex;
      gap: 10px;
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

